package com.mt.checkerin;

import java.io.IOException;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpHelper {
	
	private String webAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36";
	
	private HttpClientContext hpCtx;
	private CloseableHttpClient hpClient;
	
	public void init() {
		CookieStore cs = new BasicCookieStore();
		hpCtx = HttpClientContext.create();
		hpCtx.setCookieStore(cs);
		hpClient = HttpClients.custom()
				.setUserAgent(webAgent)
				.build();
	}
	
	public HttpHelper() {
		init();
	}

	public String sendReuqest(String url, Header... headerArr) throws ParseException, IOException {
		HttpGet request = new HttpGet(url);
		
		for (Header header : headerArr) {
			request.addHeader(header);
		}
		
		return processResponse(request);
	}

	public String sendReuqest(String url, List<NameValuePair> formParams, Header... headerArr) throws ParseException, IOException {
		
		HttpPost request = new HttpPost(url);
		for (Header header : headerArr) {
			request.addHeader(header);
		}
		
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams);
		request.setEntity(entity);
		
		
		
		return processResponse(request);
	}
	
	private String processResponse(HttpUriRequest request) throws ClientProtocolException, IOException {
		CloseableHttpResponse resp = hpClient.execute(request, hpCtx);
		System.out.println(resp.getStatusLine().getStatusCode());
		System.out.println(resp.getStatusLine().getReasonPhrase());
		HttpEntity respEnty = resp.getEntity();
		System.out.println(respEnty.getContentType());
		String pageContent = EntityUtils.toString(respEnty);
		return pageContent;
	}

}
